package org.snowin.common;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;
import org.snowin.utils.IdentifyCode;
import org.snowin.utils.ScreenCapture;

public class BaseAction
{
    protected WTDGlobal wtdGlobal;
    protected SessionData sessionData;
    protected WebDriver webDriver;
    protected String hostName;
    protected Logger logger;

    public BaseAction() {}

    public BaseAction(SessionData sessionData)
    {
        this.sessionData = sessionData;
        this.wtdGlobal = new WTDGlobal();
        this.webDriver = sessionData.getWebDriver();
        this.hostName = sessionData.getHostName();
        this.logger = sessionData.getLogger();
    }

    public String screenCapture()
    {
        String path = new ScreenCapture(this.sessionData).getPicPath();
        sleep(500);
        return path;
    }

    public String getPicCode(String bid)
    {
        IdentifyCode identifyCode = new IdentifyCode(this.sessionData);
        sleep(300);
        return identifyCode.getPicCodeVaule(bid);
    }

    public String getSmsCode(String phoneNum, String bid)
    {
        IdentifyCode identifyCode = new IdentifyCode(this.sessionData);
        sleep(300);
        return identifyCode.getSmsCodeVaule(phoneNum, bid);
    }

    protected boolean clickBy(By by)
    {
        try
        {
            WebElement el = this.webDriver.findElement(by);
            el.click();
            sleep(500);
        }
        catch (Exception e)
        {
            this.logger.error("~~~~~~~~~~~~~~ find Element:" + by.toString() + " is failed ~~~~~~~~~~~~");

            this.logger.info("Exception", e);
            return false;
        }
        return true;
    }

    protected boolean clickById(String id)
    {
        try
        {
            WebElement el = this.webDriver.findElement(By.id(id));
            el.click();
            sleep(500);
        }
        catch (Exception e)
        {
            this.logger.error("~~~~~~~~~~~~~~ find ElementById:" + id + " is failed ~~~~~~~~~~~~");

            this.logger.info("Exception", e);
            return false;
        }
        return true;
    }

    protected boolean clickByLinkText(String link)
    {
        try
        {
            WebElement el = this.webDriver.findElement(By.linkText(link));
            el.click();
            sleep(500);
        }
        catch (Exception e)
        {
            this.logger.error("~~~~~~~~~~~~~~ find ElementByLinkText:" + link + " is failed ~~~~~~~~~~~~");

            this.logger.info("Exception", e);
            return false;
        }
        return true;
    }

    protected boolean sendKeys(By by, String value)
    {
        try
        {
            WebElement el = this.webDriver.findElement(by);
            el.sendKeys(new CharSequence[] { value });
            sleep(500);
        }
        catch (Exception e)
        {
            this.logger.error("~~~~~~~~~~~~~~ find Element:" + by.toString() + " is failed ~~~~~~~~~~~~");

            this.logger.info("Exception", e);
            return false;
        }
        return true;
    }

    protected boolean sendKeysById(String id, String value)
    {
        try
        {
            WebElement el = this.webDriver.findElement(By.id(id));
            el.sendKeys(new CharSequence[] { value });
            sleep(500);
        }
        catch (Exception e)
        {
            this.logger.error("~~~~~~~~~~~~~~ find ElementById:" + id + " is failed ~~~~~~~~~~~~");

            this.logger.info("Exception", e);
            return false;
        }
        return true;
    }

    protected boolean isExist(By by)
    {
        List<WebElement> el = new ArrayList();
        try
        {
            el = this.webDriver.findElements(by);
        }
        catch (Exception e)
        {
            this.logger.error("~~~~~~~~~~~~~~ find Element:" + by.toString() + " is failed ~~~~~~~~~~~~");

            this.logger.info("Exception", e);
            return false;
        }
        return (el.size() != 0) && (null != el);
    }

    protected boolean isTextExist(String content)
    {
        List<WebElement> el = new ArrayList();
        try
        {
            el = this.webDriver.findElements(By.xpath("//*[contains(.,'" + content + "')]"));
        }
        catch (Exception e)
        {
            this.logger.error("~~~~~~~~~~~~~~ find Element:" + content + " is failed ~~~~~~~~~~~~");

            this.logger.info("Exception", e);
            return false;
        }
        return (el.size() != 0) && (null != el);
    }

    protected boolean isCurrentURL(String url)
    {
        try
        {
            if ((null == url) || (url.equals(""))) {
                return false;
            }
            String currentUrl = this.webDriver.getCurrentUrl().toLowerCase();
            if (currentUrl.endsWith("/")) {
                currentUrl = currentUrl.substring(0, currentUrl.length() - 1);
            }
            if (url.endsWith("/")) {
                url = url.substring(0, url.length() - 1);
            }
            return
                    currentUrl.toLowerCase().equals(url.toLowerCase());
        }
        catch (Exception e)
        {
            this.logger.info("Exception", e);
        }
        return false;
    }

    protected String findElVaule(By by)
    {
        WebElement el = null;
        try
        {
            el = this.webDriver.findElement(by);
        }
        catch (Exception e)
        {

            this.logger.error("~~~~~~~~~~~~~~ find Element:" + by.toString() + " is failed ~~~~~~~~~~~~");

            this.logger.info("Exception", e);
            return "";
        }

        return el.getText();
    }

    protected List<WebElement> findElements(By by)
    {
        List<WebElement> el = new ArrayList();
        try
        {
            el = this.webDriver.findElements(by);
        }
        catch (Exception e)
        {
            this.logger.error("~~~~~~~~~~~~~~ find Element:" + by.toString() + " is failed ~~~~~~~~~~~~");

            this.logger.info("Exception", e);
        }
        return el;
    }

    protected WebElement findElement(By by)
    {
        WebElement el = null;
        try
        {
            el = this.webDriver.findElement(by);
        }
        catch (Exception e)
        {
            this.logger.error("~~~~~~~~~~~~~~ find Element:" + by.toString() + " is failed ~~~~~~~~~~~~");

            this.logger.info("Exception", e);
        }
        return el;
    }

    protected WebElement findElementById(String id)
    {
        WebElement el = null;
        try
        {
            el = this.webDriver.findElement(By.id(id));
        }
        catch (Exception e)
        {
            this.logger.error("~~~~~~~~~~~~~~ find Element:" + id + " is failed ~~~~~~~~~~~~");

            this.logger.info("Exception", e);
        }
        return el;
    }

    protected void sleep(int time)
    {
        try
        {
            Thread.sleep(time);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }

    protected String getRandomPhoneNum()
    {
        String currentTime = System.currentTimeMillis() / 100L + "";
        String phoneNum = "184";
        for (int i = 3; i < currentTime.length(); i++) {
            phoneNum = phoneNum + currentTime.charAt(i);
        }
        try
        {
            Thread.sleep(100L);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        return phoneNum;
    }

    public String alertAccept()
    {
        long waitForAlert = System.currentTimeMillis() + 6000L;
        boolean boolFound = false;
        String text = "";
        do
        {
            try
            {
                Alert alert = this.webDriver.switchTo().alert();
                if (alert != null)
                {
                    text = alert.getText();
                    alert.accept();
                    boolFound = true;
                }
            }
            catch (Exception localException) {}
        } while ((System.currentTimeMillis() < waitForAlert) && (!boolFound));
        return text;
    }

    public String alertDismiss()
    {
        long waitForAlert = System.currentTimeMillis() + 6000L;
        boolean boolFound = false;
        String text = "";
        do
        {
            try
            {
                Alert alert = this.webDriver.switchTo().alert();
                if (alert != null)
                {
                    text = alert.getText();
                    alert.dismiss();
                    boolFound = true;
                }
            }
            catch (Exception localException) {}
        } while ((System.currentTimeMillis() < waitForAlert) && (!boolFound));
        return text;
    }

    public void switchNewWindow()
    {
        String currentHandle = this.webDriver.getWindowHandle();
        Set<String> windowshandles = this.webDriver.getWindowHandles();
        for (String s : windowshandles) {
            if (!s.contains(currentHandle)) {
                this.webDriver.switchTo().window(s);
            }
        }
    }
}
